<template>
  <div>
    <div class="top">
      <el-button
        type="primary"
        class="el-icon-plus add"
        size="mini"
        @click="addOrUpdata('add')"
        >新增</el-button
      >
    </div>

    <el-table :data="tableData" style="width: 100%" border>
      <el-table-column
        :prop="item.prop"
        :label="item.label"
        :width="item.width"
        align="center"
        v-for="(item, index) in supplierTableHead"
        :key="index"
      >
      </el-table-column>
      <el-table-column prop="address" label="地址" align="center">
        <template slot-scope="scope">
          <!-- 悬浮提示 -->
          <el-tooltip
            placement="top"
            :content="scope.row.address"
            :open-delay="500"
            effect="dark"
            v-if="!showTitle"
          >
            <div class="toEllipsis" @mouseover="onShowAddressTipsMouseenter">
              {{ scope.row.address }}
            </div>
          </el-tooltip>
          <div
            class="toEllipsis"
            @mouseover="onShowAddressTipsMouseenter"
            v-else
          >
            {{ scope.row.address }}
          </div>
        </template>
      </el-table-column>
      <el-table-column
        prop="state"
        label="状态"
        align="center"
        :formatter="getState"
      >
      </el-table-column>
      <el-table-column prop="remark" label="备注" align="center">
      </el-table-column>
      <el-table-column label="操作" align="center">
        <template slot-scope="{ row }">
          <el-button type="text" size="mini" @click="addOrUpdata('edit', row)"
            >修改</el-button
          >
          <el-button type="text" size="mini" @click="deleteSupplier(row.id)"
            >删除</el-button
          >
        </template>
      </el-table-column>
      <!-- 无数据 -->
      <template slot="empty">
        <div class="noData">
          <!--  v-show="data.length===0" -->
          <img src="@/assets/images/noData.png" />
          <p>暂无数据</p>
        </div>
      </template>
    </el-table>
    <Pagination :total="total" @pagination="handleSizeChange"></Pagination>
    <el-dialog :title="title" :visible.sync="dialogVisible" width="40%">
      <el-row :gutter="10">
      <el-form
        ref="form"
        :model="formData"
        label-width="92px"
        size="mini"
        inline
        :rules="ruleForm"
      >
          <el-col :span="12">
            <el-form-item label="供应商名称" prop="name">
              <el-input v-model="formData.name"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系人" prop="contactPeople">
              <el-input v-model="formData.contactPeople"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="手机号" prop="phoneNumber">
              <el-input v-model="formData.phoneNumber"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态" prop="state">
              <el-select v-model="formData.state" placeholder="">
                <el-option label="正常" value="0"> </el-option>
                <el-option label="禁用" value="1"> </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="地址" prop="area">
              <el-cascader
                :key="formData.id"
                :options="options"
                @change="handleChange"
                v-model="formData.area"
              >
              </el-cascader>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="详细地址" prop="detailAddress">
              <el-input
                v-model="formData.detailAddress"
                placeholder="请输入详细地址"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="备注">
              <el-input
                type="textarea"
                v-model="formData.remark"
                placeholder="请输入备注"
              ></el-input>
            </el-form-item>
          </el-col>
        
      </el-form>
      </el-row>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="confirm">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import cloneDeep from "lodash/cloneDeep";
import { regionData, CodeToText, TextToCode } from "element-china-area-data";
import { supplierTableHead } from "./constant";
import {
  supplierList,
  addAndUpdate,
  supplierDelete,
} from "@/api/material-management/supplier";
export default {
  data() {
    return {
      showTitle: null,
      title: "",
      dialogVisible: false,
      total: 0,
      tableData: [],
      initForm: {},
      formData: {
        area: [],
        detailAddress: "",
        address: "",
        contactPeople: "",
        id: '',
        name: "",
        pageNum: 0,
        pageSize: 10,
        phoneNumber: "",
        remark: "",
        state: "",
      },
      ruleForm: {
        name: [
          { required: true, message: "请输入供应商名称", trigger: "blur" },
        ],
        contactPeople: [
          { required: true, message: "请输入联系人", trigger: "blur" },
        ],
        phoneNumber: [
          { required: true, message: "请输入手机号码", trigger: "change" },
          {
            pattern: /^1[3|5|7|8|9]\d{9}$/,
            message: "请输入正确的号码格式",
            trigger: "change",
          },
        ],
        state: [{ required: true, message: "请选择状态", trigger: "change" }],
        area: [{ required: true, message: "请输入地址", trigger: "blur" }],
        detailAddress: [
          { required: true, message: "请输入详细地址", trigger: "blur" },
        ],
      },
      options: regionData,
      selectedOptions: [],
      supplierTableHead,
    };
  },
  created() {
    this.getTableList();
    this.initForm = cloneDeep(this.formData);
  },
  methods: {
    async getTableList(data = this.formData) {
      let res = await supplierList(data);
      if (res.code == 200) {
        this.tableData = res.data.records;
        this.total = res.data.total;
      }
    },
    getState(row) {
      let state = "";
      row.state === 0 ? (state = "禁用") : (state = "正常");
      return state;
    },
    addOrUpdata(type, row) {
      if (type == "add") {
        this.title = "新增供应商";
        this.formData = cloneDeep(this.initForm);
        this.dialogVisible = true;
        this.$nextTick(() => {
          this.$refs.form.clearValidate();
        });
      } else {
        this.title = "编辑供应商";
        //debugger;
        this.formData = Object.assign(this.formData, cloneDeep(row));
        
        let str = this.formData.address.split(",");
        this.formData.detailAddress = str[1];
        let str1 = str[0].split("/");
        let arr = [];
        arr[0] = TextToCode[str1[0]].code;
        arr[1] = TextToCode[str1[0]][str1[1]].code;
        arr[2] = TextToCode[str1[0]][str1[1]][str1[2]].code;
        this.formData.area = arr;
        this.dialogVisible = true;
      }
    },
    async deleteSupplier(id) {
      this.$alert("确定要删除？", "删除", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        showCancelButton: true,
      })
        .then(async () => {
          let res = await supplierDelete([id]);
          if (res.code == 200) {
            this.tableData.length > 1
              ? this.formData.pageNum
              : this.formData.pageNum--;
            this.getTableList(this.initForm);
          }
        })
        .catch(() => {});
    },
    handleChange(value) {
      console.log(value);
      this.formData.address =
        CodeToText[value[0]] +
        "/" +
        CodeToText[value[1]] +
        "/" +
        CodeToText[value[2]];
    },
    confirm() {
      this.$refs.form.validate(async (valid) => {
        if (valid) {
          if (this.title == "新增供应商") {
            this.formData.address =
              this.formData.address + "," + this.formData.detailAddress;
          } else {
            this.formData.address =
              this.formData.address.split(",")[0] +
              "," +
              this.formData.detailAddress;
          }
          let res = await addAndUpdate(this.formData);
          if (res.code == 200) {
            this.dialogVisible = false;
            this.getTableList(this.initForm);
            this.formData = cloneDeep(this.initForm);
          }
        } else {
          return false;
        }
      });
    },
    handleSizeChange(val) {
      this.formData.pageNum = val.page;
      this.formData.pageSize = val.limit;
      this.getTableList();
    },
    onShowAddressTipsMouseenter(e) {
      let textLength = e.target.clientWidth;
      let containerLength = e.target.scrollWidth;
      if (textLength < containerLength) {
        // 溢出了
        this.showTitle = false;
      } else {
        this.showTitle = true;
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.toEllipsis {
  white-space: nowrap; //  设置文字在一行显示不能换行
  overflow: hidden; //文字长度超过限制长度，则隐藏显示内容
  text-overflow: ellipsis; //用省略号代替被隐藏的文本
}
</style>
